<?php
/**
 * The materials class.
 * @author Andy Rich <andy.rich@gmail.com>
 * @version 1.0
 * @since 2013-10-30
 */

require_once 'database.php';
require_once 'table.php';

class material extends table {
	var $name;
	var $qty;
	var $unit;
	var $price;

	/**
	 * The constructor of the material class.
	 *
	 * @param i		The ID of this material.
	 * @return		The newly initialized material object.
	 */
	function __construct($i) {
		parent::__construct ($i,'Materials');
		$this->name 	= "";
		$this->qty 		= -1;
		$this->unit 	= "";
		$this->price	= -1;
	}

	/**
	 * Initialize this object from its data.
	 *
	 * @param _name			The name of this material.
	 * @param _qty		The qty of this material in stock.
	 * @param _unit			The unit that is represented by qty.
	 * @param _price		The price per unit of this material.
	 */
	function init_from_data($_name, $_qty, $_unit, $_price) {
		$this->name 	= $_name;
		$this->qty 		= $_qty;
		$this->unit 	= $_unit;
		$this->price 	= $_price;
	}

	/**
	 * Initialize this material object from form data.
	 *
	 * @param post	The _POST variable from a form.
	 * @return		Whether or not the intialization was successful.
	 */
	function init_from_post($post) {
		if (!(isset ($post['name']) 
			 && isset ($post['qty'])
			 && isset ($post['unit'])
			 && isset ($post['price'])))
			return FALSE;
		$this->init_from_data (
            $post['name'],
            $post['qty'],
            $post['unit'],
            $post['price']
        );
		return TRUE;
	}

	/**
	 * Displays a form to select a material from the database.
	 *
	 * @param action	The action to perform on submission.
	 */
	static function select ($action) {
		$db = new database ();
		$materials = $db->query ("SELECT id, name FROM Materials");
		echo "<form name=\"materials\" action=\"" . $action . "\" method=\"post\">\n";
		echo "<select name=\"name\">\n";
		while ($row = $materials->fetch_assoc ()) {
			$id = $row['id']; $name = $row['name'];
			echo "<option value='$id'>$name</option>\n";
		}
		$db->close ();
		echo "</select><br>";
		echo "<input type=\"submit\" value=\"Go\"><br>\n";
		echo "</form><br>\n";
	}
}

?>
